package com.gitee.feizns.webtemplate.commons.upload.processor;

import com.gitee.feizns.webtemplate.commons.upload.MediaType;
import com.gitee.feizns.webtemplate.commons.upload.UploadEvent;
import com.gitee.feizns.webtemplate.commons.upload.UploadProperties;
import com.gitee.feizns.webtemplate.commons.upload.service.MediaHandler;
import com.gitee.feizns.webtemplate.commons.utils.StreamUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author feizns
 * @since 2019/5/15
 */
public class DirHandler implements MediaHandler {

    /**
     * 处理的媒体类型
     */
    private MediaType handleMediaType;

    private Processor processor;

    public DirHandler(MediaType handleMediaType, Processor processor) {
        this.handleMediaType = handleMediaType;
        this.processor = processor;
    }

    @Override
    public final void handle(UploadEvent event, UploadProperties properties) {

        if ( event.getMediaType() == handleMediaType ) {

            String[] dirs = getDirs(properties);

            if ( dirs != null ) {
                try ( InputStream is = event.getInputStream() ) {
                    InputStream[] streams = StreamUtils.copyStream(is, dirs.length);
                    for (int i = 0; i < streams.length; i++) {
                        try ( InputStream item = streams[i] ) {
                            processor.write(UploadEvent.reset(event, is), dirs[i], properties);
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }

    }

    /**
     * 获取目录
     * @param uploadProperties
     * @return
     */
    protected final String[] getDirs(UploadProperties uploadProperties) {
        return processor.getProperty(uploadProperties).get(handleMediaType);
    }

}
